package cn.xorange.commons.quartz.controller;

import cn.xorange.commons.core.basic.bean.PageBean;
import cn.xorange.commons.core.basic.bean.ResultBean;
import cn.xorange.commons.core.basic.controller.BaseController;
import cn.xorange.commons.quartz.constants.ScheduleConstants;
import cn.xorange.commons.quartz.domain.SysJob;
import cn.xorange.commons.quartz.exception.TaskException;
import cn.xorange.commons.quartz.service.ISysJobService;
import cn.xorange.commons.quartz.util.CronUtils;
import cn.xorange.commons.quartz.util.ScheduleUtils;
import cn.xorange.commons.security.annotation.Authorize;
import cn.xorange.commons.security.utils.SecurityUtils;
import cn.xorange.commons.core.constants.SysConstants;
import cn.xorange.commons.utils.poi.excel.EasyExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 调度任务信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/job")
public class SysJobController extends BaseController {
    @Autowired
    private ISysJobService jobService;


    /**
     * 查询定时任务列表
     */
    @Authorize(hasPerm = "monitor:job:list")
    @GetMapping("/list")
    public PageBean list(SysJob sysJob)
    {
        startPage();
        List<SysJob> list = jobService.selectJobList(sysJob);
        return new PageBean(list);
    }

    /**
     * 导出定时任务列表
     */
    @Authorize(hasPerm = "monitor:job:export")
    //@Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysJob sysJob){
        List<SysJob> list = jobService.selectJobList(sysJob);
        EasyExcelUtil.exportExcel(list,"导出","导出",SysJob.class,"定时任务",response);
    }

    /**
     * 获取定时任务详细信息
     */
    @Authorize(hasPerm = "monitor:job:query")
    @GetMapping(value = "/{jobId}")
    public ResultBean getInfo(@PathVariable("jobId") Long jobId)
    {
        return ResultBean.onSuccess(jobService.selectJobById(jobId));
    }

    /**
     * 新增定时任务
     */
    @Authorize(hasPerm = "monitor:job:add")
    //@Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping
    public ResultBean add(@RequestBody SysJob job) throws SchedulerException, TaskException
    {
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return ResultBean.onFail("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), ScheduleConstants.LOOKUP_RMI))
        {
            return ResultBean.onFail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { ScheduleConstants.LOOKUP_LDAP, ScheduleConstants.LOOKUP_LDAPS }))
        {
            return ResultBean.onFail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { SysConstants.HTTP, SysConstants.HTTPS }))
        {
            return ResultBean.onFail("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), ScheduleConstants.JOB_ERROR_STR))
        {
            return ResultBean.onFail("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return ResultBean.onFail("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        job.setCreateBy(SecurityUtils.getUsername());
        return ResultBean.onSuccess(jobService.insertJob(job));
    }

    /**
     * 修改定时任务
     */
    @Authorize(hasPerm = "monitor:job:edit")
    //@Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public ResultBean edit(@RequestBody SysJob job) throws SchedulerException, TaskException
    {
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return ResultBean.onFail("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), ScheduleConstants.LOOKUP_RMI))
        {
            return ResultBean.onFail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { ScheduleConstants.LOOKUP_LDAP, ScheduleConstants.LOOKUP_LDAPS }))
        {
            return ResultBean.onFail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { SysConstants.HTTP, SysConstants.HTTPS }))
        {
            return ResultBean.onFail("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), ScheduleConstants.JOB_ERROR_STR))
        {
            return ResultBean.onFail("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return ResultBean.onFail("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        job.setCreateBy(SecurityUtils.getUsername());
        return ResultBean.onSuccess(jobService.updateJob(job));
    }

    /**
     * 定时任务状态修改
     */
    @Authorize(hasPerm = "monitor:job:changeStatus")
    //@Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public ResultBean changeStatus(@RequestBody SysJob job) throws SchedulerException
    {
        SysJob newJob = jobService.selectJobById(job.getJobId());
        newJob.setStatus(job.getStatus());
        return ResultBean.onSuccess(jobService.changeStatus(newJob));
    }

    /**
     * 定时任务立即执行一次
     */
    @Authorize(hasPerm = "monitor:job:changeStatus")
    //@Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/run")
    public ResultBean run(@RequestBody SysJob job) throws SchedulerException
    {
        boolean result = jobService.run(job);
        return result ? ResultBean.onSuccess() : ResultBean.onFail("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
    @Authorize(hasPerm = "monitor:job:remove")
    //@Log(title = "定时任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{jobIds}")
    public ResultBean remove(@PathVariable Long[] jobIds) throws SchedulerException, TaskException
    {
        jobService.deleteJobByIds(jobIds);
        return ResultBean.onSuccess();
    }
}
